package com.example.backend.controller;

import com.example.backend.common.ResultMessage;
import com.example.backend.entity.CaiPin;
import com.example.backend.service.ICaiPinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 菜品控制类
 */

@RestController
@RequestMapping("/caiPin")
public class CaiPinController {

    @Autowired
    private ICaiPinService caiPinService;
    @PostMapping
    public ResultMessage addCaiPin(@RequestBody CaiPin caiPin) {
        if(caiPinService.addCaiPin(caiPin)){
            return ResultMessage.success(caiPin,"添加成功");
        }
        return ResultMessage.error("添加失败");
    }
    @DeleteMapping("/{cpid}")
    public ResultMessage deleteCaiPin(@PathVariable Integer cpid) {
        if(caiPinService.deleteCaiPin(cpid)){
            return ResultMessage.success(null,"删除成功");
        }
        return ResultMessage.error("删除失败");
    }

    //批量删除
    @DeleteMapping("/batch")
    public ResultMessage batchDelete(@RequestBody Map<String, String> payload) {
        String cpidsStr = payload.get("cpids");
        if (cpidsStr == null || cpidsStr.isEmpty()) {
            return ResultMessage.error("缺少菜品ID");
        }

        String[] cpidArray = cpidsStr.split(",");
        List<String> cpidList = Arrays.asList(cpidArray);

        if (caiPinService.batchDeleteByIds(cpidList)) {
            return ResultMessage.success(null, "批量删除成功");
        } else {
            return ResultMessage.error("批量删除失败");
        }
    }


    @PutMapping
    public ResultMessage updateCaiPin(@RequestBody CaiPin caiPin) {
        if(caiPinService.updateCaiPin(caiPin)){
            return ResultMessage.success(caiPin,"修改成功");
        }
        return ResultMessage.error("修改失败");
    }

    @GetMapping("/{cpid}")
    public ResultMessage queryCaiPin(@PathVariable Integer cpid) {
        return ResultMessage.success(caiPinService.queryCaiPin(cpid),"查询成功");
    }

    @GetMapping
    public ResultMessage queryCaiPinList() {
        return ResultMessage.success(caiPinService.queryCaiPin(),"查询成功");
    }

    @GetMapping("/sjid/{sjid}")
    public ResultMessage queryCaiPinBySjid(@PathVariable Integer sjid) {
        return ResultMessage.success(caiPinService.queryCaiPinBySjid(sjid),"查询成功");
    }

    @GetMapping("/caipin/{yhid}")
    public ResultMessage queryCaiPinByYhid(@PathVariable Integer yhid) {
        return ResultMessage.success(caiPinService.queryCaiPinByYhid(yhid),"查询成功");
    }


    @GetMapping("/byName/{cpmc}")
    public ResultMessage queryCaiPinByName(@PathVariable String cpmc) {
        return ResultMessage.success(caiPinService.queryCaiPinByName(cpmc),"查询成功");
    }
}
